package com.paradox.aggregation.provider.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.Serializable;

@Configuration
@Slf4j
public class RabbitMqConfig {

    @Bean
    public Exchange getExchange(){
        return new TopicExchange("topicExchange",true,false);
    }

    @Bean
    public Queue getQueue1(){
        return new Queue("topic.queue1",true);
    }

    @Bean
    public Queue getQueue2(){
        return new Queue("topic.queue2",true);
    }

    @Bean
    public Binding bindingQueue1(){
        return BindingBuilder.bind(getQueue1()).to(getExchange()).with("routing.1").noargs();
    }

    @Bean
    public Binding bindingQueue2(){
        return BindingBuilder.bind(getQueue2()).to(getExchange()).with("routing.2").noargs();
    }

    @Bean
    RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate=new RabbitTemplate();
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("correlationData: " + correlationData.toString());
                if(!ack){
                    log.error("message is rejected,for {}",cause);
                }
            }
        });
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("message return!");
                log.error("return exchange: " + exchange + ", routingKey: "
                        + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
            }
        });
        configurer.configure(rabbitTemplate, connectionFactory);
        return rabbitTemplate;
    }
}
